<?php

	TekunaApplication :: load('components.model.ArticleModel');

	class AddArticle extends AbstractMVCController {
		
		protected
			$sViewClass = 'SimpleView',
			$bTranslateOutput = true,
			$bAutoloadModel = false;
			
		private
			$sMessage = '',
			$sTitle = '',
			$sText = '';
		
		
		public function display(Request $objRequest, TekunaView $objView) {

			$objView -> assign('title', $this -> sTitle);
			$objView -> assign('text', $this -> sText);
			$objView -> assign('message', $this -> sMessage);
		}
		
		
		public function validate(Request $objRequest, TekunaView $objView) {
			
			// set input data filters
			$objComplexFilter = new FilterChain(new UnixLineDelimitersFilter(), new NoScriptFilter(), new TrimFilter());
			$objRequest -> setPOSTFilter('title', $objComplexFilter);
			$objRequest -> setPOSTFilter('text', $objComplexFilter);
			
			// get request data
			$this -> sTitle = $objRequest -> getPOSTValue('title');
			$this -> sText = $objRequest -> getPOSTValue('text');
			
			// validate input data
			if ($this -> sTitle == '') {
				
				$this -> sMessage = '%error.title.empty%';
				return false;
			}
			
			if (strlen($this -> sTitle) > 100) {
			
				$this -> sMessage = '%error.title.length%';
				return false;
			}
			
			if ($this -> sText == '') {
				
				$this -> sMessage = '%error.text.empty%';
				return false;
			}
			
			if (strlen($this -> sText) > 3000) {
				
				$this -> sMessage = '%error.text.length%';
				return false;
			}
			
			// all validations OK
			return TRUE;
		}
		
		
		public function store(Request $objRequest, TekunaView $objView) {
			
			// save article with the model
			$objArticle = new ArticleModel();
			$objArticle -> date = time();
			$objArticle -> title = $this -> sTitle;
			$objArticle -> text = nl2br($this -> sText);
			$objArticle -> save();
			
			// update message and template
			$objView -> assign('message', '%article.saved%');
			$objView -> setTemplate('AddArticleSuccess.tpl');
		}


		public function error(Request $objRequest, TekunaView $objView, Exception $objException) {

			// print the exception's message
			if ($this -> sMessage == '') {
				
				$message = $objException -> getMessage();
				$this -> sMessage = "%error.exception|$message%";
			}
			
			// log exception unless it is an ControllerValidationException
			if (! $objException instanceof ControllerValidationException) {
				
				log_exception($objException);
			}
			
			// display the form
			$this -> display($objRequest, $objView);
		}
	}
